package com.raowb.common.base.services.impl;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

import com.raowb.common.base.entitys.BaseTreeEntity;
import com.raowb.common.base.services.BaseTreeService;
import com.raowb.common.util.CollectionUtil;
import com.raowb.common.util.IDUtil;

public class BaseTreeServiceImpl<M extends BaseMapper<T>, T extends BaseTreeEntity> extends BaseServiceImpl<M, T>
		implements BaseTreeService<T> {

	
	@SuppressWarnings("unchecked")
	private Class <T> entityClass = (Class <T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1]; 
	
	@Override
	public boolean save(T entity) {
		if (entity.getId() == null) {
			entity.setId(IDUtil.getSequenceId());
		}

		if (CollectionUtil.isNotEmpty(entity.getTreeChildList())) {
			for (int i=0;i<  entity.getTreeChildList().size();i++) {
				entity.getTreeChildList().get(i).setParentId(entity.getId());
				entity.getTreeChildList().get(i).setParentName(entity.getName());
				entity.getTreeChildList().get(i).setOrderNo(i+1);
			}
			
			saveBatch(CollectionUtil.convertType(entity.getTreeChildList(),entityClass));
		}

		return super.save(entity);
	}

	@Override
	public boolean update(T entity) {

		if (CollectionUtil.isNotEmpty(entity.getTreeChildList())) {
			List<Long> ids = CollectionUtil.getFieldValues(entity.getTreeChildList(),"id",Long.class);
			ids = (List<Long>) CollectionUtil.removeNull(ids);
			//删除child
			delete(new QueryWrapper<T>(null).eq("parent_id", entity.getId()).notIn("id",ids));

			for (int i=0;i<  entity.getTreeChildList().size();i++) {
				entity.getTreeChildList().get(i).setParentId(entity.getId());
				entity.getTreeChildList().get(i).setParentName(entity.getName());
				entity.getTreeChildList().get(i).setOrderNo(i+1);
				saveOrUpdate((T)entity.getTreeChildList().get(i));
			}
//			//保存或更新child
//			saveOrUpdateBatch(CollectionUtil.convertType(entity.getTreeChildList(),entityClass));
		}
		return super.update(entity);
	}
	
	
	
	
	@Override
	protected void prepareUpdate(T entity) {
		if (entity.getParentId() == null) {
			entity.setParentId(0L);
		}
		if (entity.getId() == null) {
			entity.setId(IDUtil.getSequenceId());
		}
		setHierarchy(entity);
		super.prepareUpdate(entity);
	}

	/**
	 * 
	* @Title: setHierarchy
	* @Description:设置层级关系
	* @return void    返回类型
	* @throws
	 */
	private void setHierarchy(T entity) {
		if (entity.getParentId() == null) {
			entity.setHierarchy("x" + entity.getId() + "x");
		} else {
			BaseTreeEntity parent = findById(entity.getParentId());
			if (parent == null || parent.getHierarchy() == null) {
				entity.setHierarchy("x" + entity.getId() + "x");
			} else {
				entity.setHierarchy(parent.getHierarchy() + entity.getId() + "x");
				entity.setParentName(parent.getName());
			}
		}

	}

}
